package com.github.binarywang.demo.wx.mp.controller;

import cc.openkit.common.KitUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.binarywang.demo.wx.mp.utils.StaticFinalVar;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("/order")
public class OrderController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private WxMpService wxMpService;
    @Autowired
    private JdbcTemplate jdbcTemplate;


    /**
     * 添加工单跳转
     * @param request
     * @param openid
     * @param session
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "add", produces = "text/html")
    public ModelAndView add(HttpServletRequest request,@RequestParam("openid") String openid, HttpSession session) throws Exception {
        System.out.println("My openid = " + openid);
        // 根据 openid 查询数据库是否有这个用户
        List<Map<String, Object>> list = getAppuserByOpenid(openid);
        ModelAndView mv = new ModelAndView();
        mv.setViewName(list.size()>0 ? "add" : "tphone");
        return mv;
    }

    /**
     * 查询工单跳转
     * @param request
     * @return
     */
    @RequestMapping(value = "get", produces = "text/html")
    public ModelAndView get(HttpServletRequest request) {
        return new ModelAndView("get");
    }

    /**
     * 工单列表页面跳转
     * @param request
     * @return
     */
    @RequestMapping(value = "list", produces = "text/html")
    public ModelAndView list(HttpServletRequest request) {
        return new ModelAndView("list");
    }

    /**
     *  绑定手机
     * @param request
     * @return
     */
    @RequestMapping(value = "phone", produces = "text/html")
    public ModelAndView phone(HttpServletRequest request) {
        return new ModelAndView("phone");
    }

    /**
     * 统一先授权（1）
     * @param returnUrl
     * @return
     */
    @GetMapping("/authorize")
    public String authorize(@RequestParam("returnUrl") String returnUrl){
        String url = StaticFinalVar.URL+"/order/userInfo";
        String redirectURL = wxMpService.oauth2buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_USERINFO, URLEncoder.encode(returnUrl));
        logger.info("【微信网页授权】获取code,redirectURL={}", redirectURL);
        return "redirect:" + redirectURL;
    }

    /**
     * 获取用户基本信息（1）
     */
    @GetMapping("/userInfo")
    public String userInfo(@RequestParam("code") String code,
                           @RequestParam("state") String returnUrl) throws Exception {
        logger.info("【微信网页授权】code={}", code);
        logger.info("【微信网页授权】state={}", returnUrl);
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken;
        try {
            wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
        } catch (WxErrorException e) {
            logger.info("【微信网页授权】{}", e);
            throw new Exception(e.getError().getErrorMsg());
        }
        String openId = wxMpOAuth2AccessToken.getOpenId();
        logger.info("【微信网页授权】openId={}", openId);
        logger.info("【微信网页授权】returnUrl={}", returnUrl + "?openid=" + openId);
        System.out.println(returnUrl + "?openid=" + openId);
        return "redirect:" + returnUrl + "?openid=" + openId;
    }

    /**
     * 捆绑手机授权
     * @param username 姓名
     * @param phone 手机
     * @return
     */
    @GetMapping("/bindPhone")
    public String authorize2(@RequestParam("username") String username, @RequestParam("phone") String phone){
        String url = StaticFinalVar.URL+"/order/bindPhoneUrl";

        // 拼接需要访问的 URL
        String returnUrl = StaticFinalVar.URL+"/order/bindPhoneSet/?username="+username+"&phone="+phone;
        logger.info("【准备跳转地址】returnUrl={}", returnUrl);

        // 验证并跳转
        String redirectURL = wxMpService.oauth2buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_USERINFO, URLEncoder.encode(returnUrl));
        logger.info("【微信网页授权】获取code,redirectURL={}", redirectURL);
        return "redirect:" + redirectURL;
    }

    /**
     * 绑定手机获取 openid
     */
    @GetMapping("/bindPhoneUrl")
    public String userInfo2(@RequestParam("code") String code,
                           @RequestParam("state") String returnUrl) throws Exception {
        logger.info("【微信网页授权】code={}", code);
        logger.info("【微信网页授权】state={}", returnUrl);
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken;
        try {
            wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
        } catch (WxErrorException e) {
            logger.info("【微信网页授权】{}", e);
            throw new Exception(e.getError().getErrorMsg());
        }
        String openId = wxMpOAuth2AccessToken.getOpenId();
        logger.info("【微信网页授权】openId={}", openId);
        logger.info("【微信网页授权】returnUrl={}", returnUrl + "&openid=" + openId);
        System.out.println(returnUrl + "&openid=" + openId);
        return "redirect:" + returnUrl + "&openid=" + openId;
    }

    /**
     * 绑定手机保存到数据库的方法
     * @return
     */
    @RequestMapping("/bindPhoneSet")
    public ModelAndView add(HttpServletRequest request){

        String username = request.getParameter("username");
        String phone = request.getParameter("phone");
        String openid = request.getParameter("openid");

        String sql = "insert INTO appuser(id,username,openid,user_phone,user_time) VALUES (?,?,?,?,?)";
        System.out.println(sql);

        Object args[] = {KitUtil.uuid(),username,openid,phone,new Date()};
        int temp = jdbcTemplate.update(sql, args);
        Map<String, Object> map = new HashMap<String, Object>();

        // 准备返回值
        ModelAndView mv = new ModelAndView();
        if(temp > 0){
            System.out.println("插入成功！");
            mv.setViewName("ok");
        }else{
            System.out.println("插入失败");
            mv.setViewName("err");
        }
        return mv;
    }

    /**
     * 根据 OpenId 查询对应的用户
     * @param openid
     * @return
     */
    private List<Map<String, Object>> getAppuserByOpenid(@RequestParam("openid") String openid) {
        String sql = "select * from appuser where openid = \'"+openid+"\'";
        System.out.println("Sql = " + sql);
        return jdbcTemplate.queryForList(sql);
    }

}